#include "constants.h"

int buffer[] = {
	0, 0, 0, 0, 0,
	0, 0, 0, 0, 0,
	0, 0, 0, 0, 0
};
#define NSAMPLES sizeof(buffer)

const int inv_2n = ( 0.5/NSAMPLES )*Q15;

int average( int x )
{
	static int last_x = 0;
	static int ptr = 0;
	static int result = 0;
	int oldest_x;
	int temp;

	oldest_x = buffer[ptr];
	buffer[ptr] = x;
	ptr++;
	if( ptr == NSAMPLES ) {
		ptr = 0;
	}

	temp = oldest_x + buffer[ptr];
	result -= ( temp * (long)inv_2n )>>15;
	temp = last_x + x;
	result += ( temp * (long)inv_2n )>>15;

	last_x = x;

	return result;
}

